package com.bocai.yuweiwangluo.activity;


import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.bocai.yuweiwangluo.R;
import com.bocai.yuweiwangluo.View.RoundImageView;
import com.bocai.yuweiwangluo.base.BaseActivity;
import com.bocai.yuweiwangluo.presenter.LoginPresenter;
import com.bocai.yuweiwangluo.utils.ImageLoaderUtil;
import com.bocai.yuweiwangluo.utils.SharePrefencesUtil;
import com.bocai.yuweiwangluo.utils.UrlData;
import com.bocai.yuweiwangluo.viewModel.ILoginView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * 登录页面
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener,ILoginView,CompoundButton.OnCheckedChangeListener
{
    @ViewInject(R.id.btn_login)
    Button btn_login;
    @ViewInject(R.id.et_login_tel)
    EditText et_tel;
    @ViewInject(R.id.et_login_pwd)
    EditText et_pwd;
    @ViewInject(R.id.btn_login_toregist)
    Button toRegist;
    @ViewInject(R.id.cb_login_rememberpwd)
    CheckBox rememberPwd;
    @ViewInject(R.id.rid_login_photo)
    RoundImageView photo;
    @ViewInject(R.id.tv_login_forgetpwd)
    TextView forgetPwd;
    private LoginPresenter mLoginPresenter;
    private boolean isRememberPsd=false;
    @Override
    protected int contentView()
    {
        return R.layout.activity_login;
    }

    @Override
    protected void setData()
    {
        ViewUtils.inject(this);
        initToolbar("登录");

        getLoginPresenter();
        initEvent();
    }
    private static final int MSG_SET_ALIAS = 1001;
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SET_ALIAS:
                    Log.d("TAG", "Set alias in handler.");
                    // 调用 JPush 接口来设置别名。
                    try {
                        JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                    } catch (Exception e) {

                    }
                    break;
                default:
                    Log.i("TAG", "Unhandled msg - " + msg.what);
            }
        }
    };

    /**
     * 给极光推送设置别名为user_id,实现极光推送的单个推送及定时推送
     * @param deviceId
     */
    private void setAlias(String deviceId) {
        // EditText aliasEdit = (EditText) findViewById(R.id.et_alias);
        // String alias = aliasEdit.getText().toString().trim();

        if (TextUtils.isEmpty(deviceId)) {
            //  Toast.makeText(MainActivity.this,"---------", Toast.LENGTH_SHORT).show();
            return;
        }
      /*  if (!ExampleUtil.isValidTagAndAlias(alias)) {
            Toast.makeText(PushSetActivity.this,R.string.error_tag_gs_empty, Toast.LENGTH_SHORT).show();
            return;
        }*/

        // 调用 Handler 来异步设置别名
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, deviceId));
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {


        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    Log.i("TAG", logs);
                    // 建议这里往 SharePreference 里写一个成功设置的状态。成功设置一次后，以后不必再次设置了。
                    break;
                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    Log.i("TAG", logs);
                    // 延迟 60 秒来调用 Handler 设置别名
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    break;
                default:
                    logs = "Failed with errorCode = " + code;
                    Log.e("TAG", logs);
            }

            //ExampleUtil.showToast(logs, getApplicationContext());
        }
    };

    @Override
    protected void initEvent()
    {
        super.initEvent();
        SharedPreferences sharedPreferences=getSharedPreferences("user",MODE_PRIVATE);
        String photoPath=sharedPreferences.getString("photo","");
        ImageLoaderUtil.loaderImage(UrlData.IMAGEURL+photoPath,photo,R.mipmap.photo_default);
        btn_login.setOnClickListener(this);
        toRegist.setOnClickListener(this);
        forgetPwd.setOnClickListener(this);
        rememberPwd.setOnCheckedChangeListener(this);
        et_tel.setText(SharePrefencesUtil.gettel(this));
        if("true".equals(SharePrefencesUtil.getIsRememberPsd(this)))
        {
            rememberPwd.setChecked(true);
            et_pwd.setText(SharePrefencesUtil.getPsd(this));
        }else
        {
            rememberPwd.setChecked(false);
        }
    }


    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.btn_login:
                mLoginPresenter.login();
                break;
            case R.id.btn_login_toregist:
                startActivity(new Intent(this, RegistActivity.class));
                break;
            case R.id.tv_login_forgetpwd:
                startActivity(new Intent(this, ForgetPsdActivity.class));
        }
    }

    @Override
    public boolean getRemeberPsd()
    {
        return isRememberPsd;
    }

    @Override
    public String getUserName()
    {
        return et_tel.getText().toString();
    }
    @Override
    public String getPassWord()
    {
        return et_pwd.getText().toString();
    }

    @Override
    public LoginPresenter getLoginPresenter()
    {
        mLoginPresenter=new LoginPresenter(this,this,this);
        return mLoginPresenter;
    }

    @Override
    public void callBack(String userId) {
        setAlias(userId);
    }

    @Override
    public void finishActivity()
    {
        this.finish();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        isRememberPsd=isChecked;
    }
}
